<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>NanoChat</title>
    <link rel="icon" type="image/svg+xml" href="/logo.svg">
    <style>
        :root {
            color-scheme: light;
        }

        * {
            box-sizing: border-box;
        }

        body {
            font-family: ui-sans-serif, -apple-system, system-ui, "Segoe UI", Helvetica, "Apple Color Emoji", Arial, sans-serif, "Segoe UI Emoji", "Segoe UI Symbol";
            background-color: #ffffff;
            color: #111827;
            min-height: 100vh;
            margin: 0;
            display: flex;
            flex-direction: column;
        }

        .header {
            background-color: #ffffff;
            padding: 1.25rem 1.5rem;
        }

        .header-left {
            display: flex;
            align-items: center;
            gap: 0.75rem;
        }

        .header-logo {
            height: 32px;
            width: auto;
        }

        .header h1 {
            font-size: 1.25rem;
            font-weight: 600;
            margin: 0;
            color: #111827;
        }

        .new-conversation-btn {
            width: 32px;
            height: 32px;
            padding: 0;
            border: 1px solid #e5e7eb;
            border-radius: 0.5rem;
            background-color: #ffffff;
            color: #6b7280;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: all 0.2s ease;
        }

        .new-conversation-btn:hover {
            background-color: #f3f4f6;
            border-color: #d1d5db;
            color: #374151;
        }

        .chat-container {
            flex: 1;
            overflow-y: auto;
            background-color: #ffffff;
        }

        .chat-wrapper {
            max-width: 48rem;
            margin: 0 auto;
            padding: 2rem 1.5rem 3rem;
            display: flex;
            flex-direction: column;
            gap: 0.75rem;
        }

        .message {
            display: flex;
            justify-content: flex-start;
            margin-bottom: 0.5rem;
            color: #0d0d0d;
        }

        .message.assistant {
            justify-content: flex-start;
        }

        .message.user {
            justify-content: flex-end;
        }

        .message-content {
            white-space: pre-wrap;
            line-height: 1.6;
            max-width: 100%;
        }

        .message.assistant .message-content {
            background: transparent;
            border: none;
            padding: 0.25rem 0;
        }

        .message.user .message-content {
            background-color: #f3f4f6;
            border-radius: 1.25rem;
            padding: 0.8rem 1rem;
            max-width: 65%;
        }

        .input-container {
            background-color: #ffffff;
            padding: 1rem;
        }

        .input-wrapper {
            max-width: 48rem;
            margin: 0 auto;
            display: flex;
            gap: 0.75rem;
            align-items: flex-end;
        }

        .chat-input {
            flex: 1;
            padding: 0.8rem 1rem;
            border: 1px solid #d1d5db;
            border-radius: 0.75rem;
            background-color: #ffffff;
            color: #111827;
            font-size: 1rem;
            line-height: 1.5;
            resize: none;
            outline: none;
            min-height: 54px;
            max-height: 200px;
            transition: border-color 0.2s ease, box-shadow 0.2s ease;
        }

        .chat-input::placeholder {
            color: #9ca3af;
        }

        .chat-input:focus {
            border-color: #2563eb;
            box-shadow: 0 0 0 3px rgba(37, 99, 235, 0.1);
        }

        .send-button {
            flex-shrink: 0;
            padding: 0;
            width: 54px;
            height: 54px;
            border: 1px solid #111827;
            border-radius: 0.75rem;
            background-color: #111827;
            color: #ffffff;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            transition: background-color 0.2s ease, border-color 0.2s ease, color 0.2s ease;
        }

        .send-button:hover:not(:disabled) {
            background-color: #2563eb;
            border-color: #2563eb;
        }

        .send-button:disabled {
            cursor: not-allowed;
            border-color: #d1d5db;
            background-color: #e5e7eb;
            color: #9ca3af;
        }

        .typing-indicator {
            display: inline-block;
            color: #6b7280;
            letter-spacing: 0.15em;
        }

        .typing-indicator::after {
            content: '···';
            animation: typing 1.4s infinite;
        }

        @keyframes typing {
            0%, 60%, 100% { opacity: 0.2; }
            30% { opacity: 1; }
        }

        .error-message {
            background-color: #fee2e2;
            border: 1px solid #fecaca;
            color: #b91c1c;
            padding: 0.75rem 1rem;
            border-radius: 0.75rem;
            margin-top: 0.5rem;
        }
    </style>
</head>
<body>
    <div class="header">
        <div class="header-left">
            <button class="new-conversation-btn" onclick="newConversation()" title="New Conversation (Ctrl+Shift+N)">
                <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                    <path d="M12 5v14"></path>
                    <path d="M5 12h14"></path>
                </svg>
            </button>
            <h1>nanochat</h1>
        </div>
    </div>

    <div class="chat-container" id="chatContainer">
        <div class="chat-wrapper" id="chatWrapper">
            <!-- Messages will be added here -->
        </div>
    </div>

    <div class="input-container">
        <div class="input-wrapper">
            <textarea
                id="chatInput"
                class="chat-input"
                placeholder="Ask anything"
                rows="1"
                onkeydown="handleKeyDown(event)"
            ></textarea>
            <button id="sendButton" class="send-button" onclick="sendMessage()" disabled>
                <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                    <path d="M22 2L11 13"></path>
                    <path d="M22 2l-7 20-4-9-9-4 20-7z"></path>
                </svg>
            </button>
        </div>
    </div>

    <script>
        const API_URL = '';
        const chatContainer = document.getElementById('chatContainer');
        const chatWrapper = document.getElementById('chatWrapper');
        const chatInput = document.getElementById('chatInput');
        const sendButton = document.getElementById('sendButton');

        let messages = [];
        let isGenerating = false;

        chatInput.addEventListener('input', function() {
            this.style.height = 'auto';
            this.style.height = Math.min(this.scrollHeight, 200) + 'px';
            sendButton.disabled = !this.value.trim() || isGenerating;
        });

        function handleKeyDown(event) {
            if (event.key === 'Enter' && !event.shiftKey) {
                event.preventDefault();
                sendMessage();
            }
        }

        document.addEventListener('keydown', function(event) {
            // Ctrl+Shift+N for new conversation
            if (event.ctrlKey && event.shiftKey && event.key === 'N') {
                event.preventDefault();
                if (!isGenerating) {
                    newConversation();
                }
            }
        });

        function newConversation() {
            messages = [];
            chatWrapper.innerHTML = '';
            chatInput.value = '';
            chatInput.style.height = 'auto';
            sendButton.disabled = false;
            isGenerating = false;
            chatInput.focus();
        }

        function addMessage(role, content) {
            const messageDiv = document.createElement('div');
            messageDiv.className = `message ${role}`;

            const contentDiv = document.createElement('div');
            contentDiv.className = 'message-content';
            contentDiv.textContent = content;

            messageDiv.appendChild(contentDiv);
            chatWrapper.appendChild(messageDiv);

            chatContainer.scrollTop = chatContainer.scrollHeight;
            return contentDiv;
        }

        async function sendMessage() {
            const message = chatInput.value.trim();
            if (!message || isGenerating) return;

            isGenerating = true;
            chatInput.value = '';
            chatInput.style.height = 'auto';
            sendButton.disabled = true;

            messages.push({ role: 'user', content: message });
            addMessage('user', message);

            const assistantContent = addMessage('assistant', '');
            assistantContent.innerHTML = '<span class="typing-indicator"></span>';

            try {
                const response = await fetch(`${API_URL}/chat/completions`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        messages: messages,
                        stream: true,
                        temperature: 0.8,
                        max_tokens: 512
                    }),
                });

                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }

                const reader = response.body.getReader();
                const decoder = new TextDecoder();
                let fullResponse = '';
                assistantContent.textContent = '';

                while (true) {
                    const { done, value } = await reader.read();
                    if (done) break;

                    const chunk = decoder.decode(value);
                    const lines = chunk.split('\n');

                    for (const line of lines) {
                        if (line.startsWith('data: ')) {
                            try {
                                const data = JSON.parse(line.slice(6));
                                if (data.token) {
                                    fullResponse += data.token;
                                    assistantContent.textContent = fullResponse;
                                    chatContainer.scrollTop = chatContainer.scrollHeight;
                                }
                            } catch (e) {
                            }
                        }
                    }
                }

                messages.push({ role: 'assistant', content: fullResponse });

            } catch (error) {
                console.error('Error:', error);
                assistantContent.innerHTML = `<div class="error-message">Error: ${error.message}</div>`;
            } finally {
                isGenerating = false;
                sendButton.disabled = !chatInput.value.trim();
            }
        }

        sendButton.disabled = false;

        // Autofocus the chat input on page load
        chatInput.focus();

        fetch(`${API_URL}/health`)
            .then(response => response.json())
            .then(data => {
                console.log('Engine status:', data);
            })
            .catch(error => {
                console.error('Engine not available:', error);
                chatWrapper.innerHTML = '<div class="error-message">Engine not running. Please start engine.py first.</div>';
            });
    </script>
</body>
</html>
